package com.sgzn.sgpay.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.sgzn.sgpay.enums.MerchantAccountStat;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.exception.SgpayException;
import com.sgzn.sgpay.model.request.SgsMchQueryListRequest;
import com.sgzn.sgpay.model.request.SgsMerchantQueryBalanceRequest;
import com.sgzn.sgpay.model.request.SgsMerchantQueryBaseRequest;
import com.sgzn.sgpay.model.request.SgsSubMchQueryRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.result.MchQueryBalanceResult;
import com.sgzn.sgpay.model.response.result.MerchantInfo;
import com.sgzn.sgpay.model.response.result.SubMchQueryResult;
import com.sgzn.sgpay.model.response.vo.PrivilegeVo;
import com.sgzn.sgpay.model.response.vo.ShopVo;
import com.sgzn.sgpay.persistence.dao.TMerchantAccountMapper;
import com.sgzn.sgpay.persistence.dao.TMerchantMapper;
import com.sgzn.sgpay.persistence.domain.TMerchant;
import com.sgzn.sgpay.persistence.domain.TMerchantAccount;
import com.sgzn.sgpay.persistence.domain.TMerchantAccountExample;
import com.sgzn.sgpay.persistence.domain.TMerchantExample;
import com.sgzn.sgpay.service.SgsMerchantQueryService;
import com.sgzn.sgpay.service.converter.MerchantResponseConverter;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.service.support.SubMchManager;
import com.sgzn.sgpay.util.ArgsUtils;
import com.sgzn.sgpay.util.TranslateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商户查询服务
 * @author zhongzhongyong
 * @version Id: SgsMerchantQueryServiceImpl.java, v 0.1 2018/4/18 22:23 zhongzhongyong Exp $$
 */
@Slf4j
@Service
public class SgsMerchantQueryServiceImpl implements SgsMerchantQueryService {

    @Autowired
    private TMerchantMapper tMerchantMapper;

    @Autowired
    private TMerchantAccountMapper tMerchantAccountMapper;

    @Autowired
    private SubMchManager subMchManager;

    /**
     * 查询单个商户基本信息以及账户信息
     * @param request
     * @return
     */
    @Override
    public SgsResultResponse<MerchantInfo> queryMerchantInfo(SgsMerchantQueryBaseRequest request) {
        try {
            //查询商户基础信息
            TMerchantExample tMerchantExample = new TMerchantExample();
            TMerchantExample.Criteria tMchCrit = tMerchantExample.createCriteria();
            tMchCrit.andMerchantIdEqualTo(request.getMchId());
            List<TMerchant> tMerchantList = tMerchantMapper.selectByExample(tMerchantExample);
            if(CollectionUtils.isEmpty(tMerchantList)){
                throw new SgpayException(SgsResponseCode.C_MERCHANT_NOT_FOUND.getResponseCode(),
                        SgsResponseCode.C_MERCHANT_NOT_FOUND.getResponseDesc());
            }
            //查询商户账户信息
            TMerchantAccountExample tMerchantAccountExample = new TMerchantAccountExample();
            TMerchantAccountExample.Criteria tMchAccCrit = tMerchantAccountExample.createCriteria();
            tMchAccCrit.andMerchantIdEqualTo(request.getMchId());
            tMchAccCrit.andAccountStateEqualTo(MerchantAccountStat.VALID.getCode());
            List<TMerchantAccount> tMchAccList = tMerchantAccountMapper.selectByExample(tMerchantAccountExample);
            if(CollectionUtils.isEmpty(tMchAccList)){
                throw new SgpayException(SgsResponseCode.C_MCH_NOT_FOUND.getResponseCode(),
                        SgsResponseCode.C_MCH_NOT_FOUND.getResponseDesc());
            }
            //组装信息
            return SgsResponseUtil.INSTANCE.success(MerchantResponseConverter.assembleMerchantInfo(tMerchantList.get(0),tMchAccList.get(0)));
        }catch (Exception e){
            log.error("[{}]. 商户信息查询异常.", request.getInitiationID(),e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_DB_EXCEPTION.getResponseCode(),
                    SgsResponseCode.C_DB_EXCEPTION.getResponseDesc());
        }
    }
    /**
     * 查询商户基础信息列表
     * @param request
     * @return
     */
    @Override
    public SgsResultResponse<List<TMerchant>> queryMchBaseList(SgsMchQueryListRequest request) {
        try {
            //查询商户基础信息
            TMerchantExample tMerchantExample = new TMerchantExample();
            TMerchantExample.Criteria tMchCrit = tMerchantExample.createCriteria();
            if(StringUtils.isNotBlank(request.getMchType())){
                tMchCrit.andMchTypeEqualTo(request.getMchType());
            }
            tMchCrit.andParentMchIdEqualTo(request.getMchId());
            List<TMerchant> tMerchantList = tMerchantMapper.selectByExample(tMerchantExample);
            //组装信息
            return SgsResponseUtil.INSTANCE.success(tMerchantList);
        }catch (Exception e){
            log.error("[{}]. 商户信息查询异常.", request.getInitiationID(),e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_DB_EXCEPTION.getResponseCode(),
                    SgsResponseCode.C_DB_EXCEPTION.getResponseDesc());
        }
    }

    /**
     * 返回商户余额信息
     */
    @Override
    public SgsResultResponse<MchQueryBalanceResult> queryMerchantBalanceInfo(SgsMerchantQueryBalanceRequest request) {
        try{
            SgsMerchantQueryBaseRequest sgsMerchantQueryBaseRequest = new SgsMerchantQueryBaseRequest();
            sgsMerchantQueryBaseRequest.setLoginChannel(request.getLoginChannel());
            sgsMerchantQueryBaseRequest.setInitiationID(request.getInitiationID());
            sgsMerchantQueryBaseRequest.setReqTime(request.getReqTime());
            sgsMerchantQueryBaseRequest.setMchId(request.getMchId());
            SgsResultResponse<MerchantInfo> sgsResultResponse = queryMerchantInfo(sgsMerchantQueryBaseRequest);


            MchQueryBalanceResult mchQueryBalanceResult = new MchQueryBalanceResult();
            if ( sgsResultResponse.getResult().getBankCardNo() != null){
                mchQueryBalanceResult.setBindBankCardMark("1"); //表示已经绑定银行卡
            }else {
                mchQueryBalanceResult.setBindBankCardMark("0");//表示还没有绑定银行卡
            }
            mchQueryBalanceResult.setMerchantBalance(sgsResultResponse.getResult().getAccountAmount().toString() );
            if(TranslateUtil.isSuccessAbs(sgsResultResponse.getErrorCode())){
                //组装信息
                return SgsResponseUtil.INSTANCE.success(mchQueryBalanceResult);
            }else{
                return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_MCH_BAN_QUERY_FAIL.getResponseCode(),
                        SgsResponseCode.C_MCH_BAN_QUERY_FAIL.getResponseDesc());
            }
        }catch (Exception e){
            log.error("[{}]. 商户余额查询异常.", request.getInitiationID(),e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C_DB_EXCEPTION.getResponseCode(),
                    SgsResponseCode.C_DB_EXCEPTION.getResponseDesc());
        }
    }

    /**
     * 查询单个子商户信息（包含功能权限和门店权限信息）
     * @param request
     * @return
     */
    @Override
    public SgsResultResponse<SubMchQueryResult> querySubMchInfo(SgsSubMchQueryRequest request) {
        try{
            String subMchId = request.getSubMchId();
            //查询子商户基础信息
            TMerchant subMch = subMchManager.getSubMchBaseInfo(subMchId);

            //全部功能权限
            List<PrivilegeVo> allPrivList = subMchManager.getMainMchPrivList(request.getMchId(),
                    request.getLoginChannel(),request.getReqTime(),request.getInitiationID());

            //全部场地权限
            List<ShopVo> allShopList = subMchManager.getMainMchShopList(
                    request.getLoginChannel(),request.getReqTime(),request.getInitiationID(), request.getMchId());

            //已选功能权限ID集合
            List<String> selectedPrivIdList = subMchManager.getSubMchPrivList(subMchId);

            //已选场地权限ID集合
            List<String> selectedShopIdList = subMchManager.getSubMchShopList(subMchId);

            SubMchQueryResult result = new SubMchQueryResult();
            result.setMobile(subMch.getContact());
            result.setMchName(subMch.getMerchantName());
            result.setAllPrivList(allPrivList);
            result.setAllShopList(allShopList);
            result.setSelectedPrivIdList(selectedPrivIdList);
            result.setSelectedShopIdList(selectedShopIdList);
            return SgsResponseUtil.INSTANCE.success(result);
        }catch (Exception e){
            log.error("[{}]. 子账户查询异常.", request.getInitiationID(),e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503000.getResponseCode(),
                    SgsResponseCode.C503000.getResponseDesc());
        }
    }


}
